package com.hbnu.ojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.hbnu.ojcodesandbox.model.ExecuteCodeRequest;
import com.hbnu.ojcodesandbox.model.ExecuteCodeResponse;
import com.hbnu.ojcodesandbox.model.ExecuteMessage;
import com.hbnu.ojcodesandbox.model.JudgeInfo;
import com.hbnu.ojcodesandbox.security.DenySecurityManager;
import com.hbnu.ojcodesandbox.utils.ProcessUtils;
import org.springframework.util.StopWatch;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Stream;


/**
 * @Description: Java本地代码沙箱
 * @Author: Hu Bowen
 */
public class JavaNativeCodeSandbox implements CodeSandbox {

    // 全局代码名称
    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";

    // 新线程的时间监控
    private static final long TIME_OUT = 5000L;  // 超时时间

    // 安全管理环境
    private static final String SECURITY_MANAGER_PATH = "C:\\code\\oj-code-sandbox\\src\\main" +
            "\\resources\\security";

    private static final String SECURITY_MANAGER_CLASS_NAME = "MySecurityManager";

    // 黑名单命令
    private static final List<String> blackList = Arrays.asList("Files", "exec");

    // 字典树
    private static final WordTree WORD_TREE;
    static {
        // 校验代码, 检验代码是否包含黑名单的命令
        WORD_TREE = new WordTree();
        // 存储黑名单的字典树
        WORD_TREE.addWords(blackList);
    }

    private static final Boolean FIRST_INIT = true;

    /**
     * 测试程序
     */
    public static void main(String[] args) {
        JavaNativeCodeSandbox javaNativeCodeSandbox = new JavaNativeCodeSandbox();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "2 3"));

        // ! 指定程序的读取路径, 测试

        // 读取resource路径下的文件, 指定读取字符集utf-8
        // String code = ResourceUtil.readStr("testCode/simpleComputeArgs/Main.java",StandardCharsets.UTF_8);

        String code = ResourceUtil.readStr("testCode/unsafeCode/ReadError.java",
                StandardCharsets.UTF_8);

        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandbox.executeCode(executeCodeRequest);
        System.out.println(executeCodeResponse); // 响应 null
    }

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        // 设置安全管理, 代码的对于系统权限的访问限制
        System.setSecurityManager(new DenySecurityManager());


        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();
        String language = executeCodeRequest.getLanguage();

        // 检查代码是否包含添加的关键词
        FoundWord foundWord = WORD_TREE.matchWord(code);
        // 判断不为空, 就表示包含这个敏感词
        if (foundWord != null) {
            // 输出敏感词
            System.out.println("包含敏感词: " + foundWord.getFoundWord());
            return null;
        }


        // 1. 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        // File.separator文件分隔符常量
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;

        // 判断全局代码是否存在, 没有则新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }

        // 把用户的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        // 2. 编译代码, 得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s",
                userCodeFile.getAbsolutePath());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(executeMessage);
        } catch (Exception e) {
            return getErrorResponse(e);
        }

        // 3. 执行代码, 得到输出结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            // 模拟用户输入用例
            // String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s Main %s",
            //         userCodeParentPath, inputArgs);

            // 指定最大的内存空间限制
            // String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s",
            //         userCodeParentPath, inputArgs);

            // !!只限制子程序的权限控制
            String runCmd = String.format("java -Dfile.encoding=UTF-8 -cp %s;%s -Djava.security.manager=MySecurityManager Main",
                    userCodeParentPath, inputArgs);

            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);

                // 创建一个新的线程, 先睡眠执行超时时间, 如果还未执行完毕, 就终止这个程序
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        System.out.println("执行超时了, 中断程序");
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }).start(); // 开启

                // 执行运行的信息
                ExecuteMessage executeMessage =
                        ProcessUtils.runInteractProcessAndGetMessage(runProcess, "运行", inputArgs);
                // ExecuteMessage executeMessage =
                //         ProcessUtils.runInteractProcessAndGetMessage(runProcess,  inputArgs);

                System.out.println(executeMessage);
                executeMessageList.add(executeMessage);
            } catch (Exception e) {
                return getErrorResponse(e);
            }
        }

        // 4. 收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 取用时最大值, 便于判断是否超时
        long maxTime = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeMessage.setMessage(errorMessage);
                executeCodeResponse.setStatus(3); // todo 执行中存在错误, 状态码
                // 用户提交时存在的错误
                break;
            }
            // 正确的信息
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }

        if (outputList.size() == executeMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }

        // 执行代码响应设置输出用例和状态
        executeCodeResponse.setOutputList(outputList);
        executeCodeResponse.setStatus(1);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        // 要借助第三方库来获取内存, 非常麻烦
        // judgeInfo.setMemory();
        executeCodeResponse.setJudgeInfo(judgeInfo);

        // 5. 文件清理
        // 判断文件的父目录不为空, 执行删除
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeParentPath);
            System.out.println("删除" + (del ? "成功" : "失败"));
        }
        return executeCodeResponse;
    }

    // 6. 错误处理, 提升程序健壮


    /**
     * 获取错误响应
     *
     * @param e
     * @return executeCodeResponse
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
        // 用户没有执行, 在编译中就存在的错误
    }
}
